//
//  BtUtils.m
//  BaiduTravel
//
//  Copyright 2011年 Neusoft. All rights reserved.
//

#import "BtUtils.h"
#import "BTDefines.h"
#import "NSArray+EX.h"
#import "EmoticonUtils.h"
#import "UIDevice-Hardware.h"
#import "DeviceIdentifier.h"
#import "TravelException.h"


#define kNoteTalkFrameImageFile                 @"image_whitemessagebody.png"
#define kTalkFrameImageFile                     @"image_whitebody.png"
#define textSingleLinePlaceHolderHeight			18  

#import <CommonCrypto/CommonDigest.h> // Need to import for CC_MD5 access
#import "regex.h"



@implementation StringObject
@synthesize value   = _value;
@synthesize type    = _type;

-(id) initWithValue:(NSString*)value
           withType:(EStringObjectType)type
{
    self = [super init];
    if( self )
    {
        self.value  = value;
        self.type   = type;
    }
    return self;
}

-(CGSize) sizeWithFont:(UIFont*)font
{
    CGSize size = CGSizeZero;
    switch (_type)
    {
        case StringObjectText:
            size = [_value sizeWithFont:font];
            break;
        case StringObjectImage:
            size = CGSizeMake(font.lineHeight,font.lineHeight);
            break;
        default:
            break;
    }
    return size;
}

-(CGSize) drawInRect:(CGRect)rect withFont:(UIFont*)font
{
    CGSize size = CGSizeZero;
    switch (_type)
    {
        case StringObjectText:
            size = [_value drawInRect:rect withFont:font];
            break;
        case StringObjectImage:
        {
            NSString *imageName = [EmoticonUtils getEmoticonFileNameByText:_value];
            UIImage *image = [UIImage imageNamed:imageName];
            [image drawInRect:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
            size = rect.size;
            break;
        }
        default:
            break;
    }
    return size;
}


-(void)dealloc
{
    [_value release];
    [super dealloc];
}
@end

@implementation NSString (MyExtensions)
- (NSString *) md5
{
    const char *cStr = [self UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, strlen(cStr), result ); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3], 
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];  
    
}

- (CGSize)customDraw:(BOOL)isOnlyHight withFont:(UIFont*)font rect:(CGRect)rect lineBreakMode:(UILineBreakMode)lineBreakMode
{
    CGFloat baseX    = rect.origin.x;
    CGFloat baseY    = rect.origin.y;
    CGFloat maxWidth = rect.size.width;
    CGFloat maxHeight = rect.size.height;
    
    CGFloat currentX = 0;
    CGFloat currentY = 0;
    CGFloat currentLineHeight = 0;
    
    NSString *dotString = @"...";
    CGSize dotStringSize = [dotString sizeWithFont:font];
    
    NSArray *array = [BtUtils buildStringObjectArray:self];
    for( StringObject *stringObject in array )
    {
     
        CGSize size = [stringObject sizeWithFont:font];
        if( (lineBreakMode ==UILineBreakModeTailTruncation)&& (currentX+size.width+dotStringSize.width>maxWidth) && (currentY+currentLineHeight+size.height>maxHeight))
        {
            //超过了，打点
            if(!isOnlyHight)
            {
                [dotString drawInRect:CGRectMake(baseX+currentX, baseY+currentY, dotStringSize.width, dotStringSize.height)
                             withFont:font];
                break;
            }
        }
        if( (currentX + size.width) > maxWidth)
        {//超过了，下一行
            currentX = 0;
            currentY += currentLineHeight;
            currentLineHeight = 0;
            if(currentY+size.height>maxHeight)
            {
                //超过height,不再绘制
                break;
            }
            
            if(!isOnlyHight)
            {
                [stringObject drawInRect:CGRectMake(baseX+currentX, baseY+currentY, size.width, size.height)
                                      withFont:font];
            }
            currentX = size.width;
            currentLineHeight = size.height;
        }
        else
        {
            //不超过，继续
            if( currentLineHeight< size.height )
            {
                currentLineHeight = size.height;
            }
            if(!isOnlyHight)
            {
                [stringObject drawInRect:CGRectMake(baseX+currentX, baseY+currentY, size.width, size.height)
                                withFont:font];
            }
            currentX += size.width;
        }
    }
    
    return CGSizeMake(maxWidth, currentY+currentLineHeight); 
}

- (CGSize)customDraw:(BOOL)isOnlyHight withFont:(UIFont*)font rect:(CGRect)rect
{
    return [self customDraw:isOnlyHight withFont:font rect:rect lineBreakMode:UILineBreakModeWordWrap];
}

- (CGSize)customSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size // Uses UILineBreakModeWordWrap
{
    return [self customDraw:YES withFont:font rect:CGRectMake(0, 0, size.width, size.height)];
}

- (CGSize)customDrawInRect:(CGRect)rect withFont:(UIFont *)font
{
    return [self customDraw:NO withFont:font rect:rect];
}

- (CGSize)customDrawInRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode // Uses UITextAlignmentLeft
{
    return [self customDraw:NO withFont:font rect:rect lineBreakMode:lineBreakMode];
}

@end



@implementation NSData (MyExtensions)

- (NSString*)md5
{
    unsigned char result[16];
    CC_MD5( self.bytes, self.length, result ); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3], 
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];  
}
@end

@implementation BtUtils

+ (NSString*) substringWithMaxThirtyChars:(NSString*)str
{
    if( [str length]>35)
    {
        NSString *retStr = [NSString stringWithFormat:@"%@...",[str substringWithRange:NSMakeRange(0,30)]];
        return retStr;
    }
    return str;
}

+ (NSString*) substringWithMaxChars:(NSString*)str
                           maxChars:(int)aMaxChars
{
    if( [str length] > aMaxChars)
    {
        NSString *retStr = [NSString stringWithFormat:@"%@...",[str substringWithRange:NSMakeRange(0,aMaxChars)]];
        return retStr;
    }
    return str;
}


+ (int)calculateContentHeight:(NSString*)aText
                 contentWidth:(int)aContentWidth
                maxContentHeight:(int)aMaxContentHeight
                     maxChars:(int)aMaxChars
                     fontSize:(int)aFontSize
{
    NSString *str = nil;
    if (aMaxChars == 30) {
        str = [BtUtils substringWithMaxThirtyChars:aText];
    }
    else
    {
        str = [BtUtils substringWithMaxChars:aText maxChars:aMaxChars];
    }
    CGSize textSize = [str sizeWithFont:[UIFont systemFontOfSize:aFontSize] 
                        constrainedToSize:CGSizeMake(aContentWidth, aMaxContentHeight)];
    return (int)textSize.height;
}

+ (NSString*)getFormattedStartTime:(NSDate*)aDate
{
	//2011年5月
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setDateFormat:@"yyyy年MM月"];
	NSString *dateStr = [dateFormatter stringFromDate:aDate];
	[dateFormatter release];
	return dateStr;
}


+(NSString*)getDetailFormattedCreateTime:(NSDate*)aDate
{
	//2011-05-06 07:05
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"YYYY.MM.dd HH:mm"];
    
	NSString *dateStr = [dateFormatter stringFromDate:aDate];
	[dateFormatter release];
	return dateStr;
}

+(NSString*)getShortFormattedCreateTime:(NSDate*)aDate
{
	//2011-05-06 07:05
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"YYYY.MM.dd"];
    
	NSString *dateStr = [dateFormatter stringFromDate:aDate];
	[dateFormatter release];
	return dateStr;
}

+(NSString*)getYearAndMonthFormattedCreateTime:(NSDate*)aDate
{
	//2011-05-06 07:05
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"YYYY.MM"];
    
	NSString *dateStr = [dateFormatter stringFromDate:aDate];
	[dateFormatter release];
    return dateStr;
}

/*
+(NSString*)getFormattedCreateTimeWithToday:(NSDate*)aDate
{
	//2011-05-06 07:05
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    if([aDate isToday])
    {
        [dateFormatter setDateFormat:@"今天 HH:mm"];
    }else if([aDate isYesterday])
    {
        [dateFormatter setDateFormat:@"昨天 HH:mm"];
    } else {
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    }
    
	NSString *dateStr = [dateFormatter stringFromDate:aDate];
	[dateFormatter release];
	return dateStr;
}
*/
+ (UIImage*)getTalkFrameImage:(int)height
{
    if(height<60)
    {
        return [UIImage imageNamed:kTalkFrameImageFile];
    }
    else
    {
        return [[UIImage imageNamed:kTalkFrameImageFile] stretchableImageWithLeftCapWidth:0 topCapHeight:3];
    }
}

+ (UIImage*)getNoteTalkFrameImage:(int)height
{
    if(height<60)
    {
        return [UIImage imageNamed:kNoteTalkFrameImageFile];
    }
    else
    {
        return [[UIImage imageNamed:kNoteTalkFrameImageFile] stretchableImageWithLeftCapWidth:0 topCapHeight:3];
    }
}


+ (NSArray*) buildStringObjectArray:(NSString*)string
{
    NSArray *emoticonArray = [EmoticonUtils getEmoticonTextArray];
    NSMutableArray *objectArray = [NSMutableArray array];
    NSMutableString *tempString = [NSMutableString stringWithString:string];
    while( [tempString length] >0 )
    {
        int emoticonFoundIndex = -1;
        for( int i = 0; i<[emoticonArray count]; ++i )
        {
            NSString *emot = [emoticonArray objectAtIndex:i withDefaultValue:nil];
            if( [tempString rangeOfString:emot].location == 0 )
            {
                emoticonFoundIndex = i;
                //发现了表情
                tempString = [NSString stringWithString:[tempString substringFromIndex:[emot length]]];
                StringObject *obj = [[[StringObject alloc] initWithValue:emot withType:StringObjectImage] autorelease];
                [objectArray addObject:obj withDefaultValue:nil];
                break;
            }
        }
        
        if( emoticonFoundIndex == -1 )
        {
            //没找到表情，提取一个字符
            NSString *textString = [NSString stringWithString:[tempString substringToIndex:1]];
            tempString = [NSString stringWithString:[tempString substringFromIndex:1]];
            StringObject *obj = [[[StringObject alloc] initWithValue:textString withType:StringObjectText] autorelease];
            [objectArray addObject:obj withDefaultValue:nil];
        }

    }
    
    return objectArray;
}

+(NSString *)getRemarkScoreFace:(NSInteger)score
{
    NSString *iconName = nil;
    switch (score) {
        case 1:
            break;
        case 2:
            iconName = @"ic_comment_rating1.png";
            break;
        case 3:
            iconName = @"ic_comment_rating2.png";
            break;
        case 4:
            iconName = @"ic_comment_rating3.png";
            break;
        case 5:
            iconName = @"ic_comment_rating4.png";
            break;
        default:
            break;
    }
    return iconName;
}

+(NSString *)getRemarkScoreText:(NSInteger)score
{
    NSString *textName = nil;
    switch (score) {
        case 1:
            break;
        case 2:
            textName = @"不喜欢";
            break;
        case 3:
            textName = @"没感觉";
            break;
        case 4:
            textName = @"还不错";
            break;
        case 5:
            textName = @"太赞啦";
            break;
        default:
            break;
    }
    return textName;
}
@end
